﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wise.Util;

namespace Wise.Entities
{
    public class MyConverter
    {
        #region 时间日期格式相关
        public static string GetTime(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return "00:00";
            if (val is DateTime || val is DateTime?)
                return (val as DateTime?).Value.ToString("HH:mm");
            return DateTime.Parse(val.ToString()).ToString("HH:mm");
        }

        public static string ToTime(int hour, int minute)
        {
            return new DateTime(1900, 1, 1, hour, minute, 0).ToString("HH:mm");
        }

        public static DateTime yyyyMMdd(object val, DataRow _row)
        {
            string strVal = val.ToString();
            if (NullHelper.IsDbNull(val))
            {
                return new DateTime(1900, 1, 1);
            }
            else if (strVal.StartsWith("year", StringComparison.CurrentCultureIgnoreCase))
            {
                #region  //year 1971
                strVal = RegexHelper.GetNumber(strVal);
                int year = int.Parse(strVal);
                if (year < 1000)
                    year += 1900;
                else if (year > 9999)
                    year = 1900;
                #endregion
                return new DateTime(year, 1, 1);
            }
            else if (strVal.IndexOf("/") > 0)
            {
                if (strVal == "31/11/1980")
                    return new DateTime(1980, 11, 30);
                #region //10/08/xxxx
                string _day = string.Join("", strVal.Take(2));
                if (!RegexHelper.IsNumber(_day))
                    _day = "01";
                string _month = string.Join("", strVal.Skip(3).Take(2));
                if (!RegexHelper.IsNumber(_month))
                    _month = "01";
                string year = string.Join("", strVal.Skip(6).Take(4));
                if (!RegexHelper.IsNumber(year))
                    year = "1900";
                #endregion
                return new DateTime(int.Parse(year), int.Parse(_month), int.Parse(_day));
            }
            else if (strVal.IndexOf(" ") >= 0)
            {
                if (strVal.Length == 10)
                {
                    #region   //12 Mar 197	
                    string[] pts = strVal.Split(' ');
                    string year = null, month = null, day = null;
                    for (int i = 0; i < pts.Length; i++)
                    {
                        string item = pts[i];
                        if (RegexHelper.IsNumber(item))
                        {
                            if (item.Length <= 2)
                            {
                                day = item;
                            }
                            else
                            {
                                year = item;
                            }
                        }
                        else if (item.StartsWith("x"))
                        {
                            year = "0";
                        }
                        else
                        {
                            month = item;
                        }
                    }
                    if (year == null)
                        year = "0";
                    if (month == null)
                        month = "1";
                    int mon = 1;
                    switch (month.ToUpper())
                    {
                        default:
                        case "JAN":
                            mon = 1;
                            break;
                        case "FEB":
                            mon = 2;
                            break;
                        case "MAR":
                            mon = 3;
                            break;
                        case "APR":
                            mon = 4;
                            break;
                        case "MAY":
                            mon = 5;
                            break;
                        case "JUN":
                            mon = 6;
                            break;
                        case "JUL":
                            mon = 7;
                            break;
                        case "AUG":
                            mon = 8;
                            break;
                        case "SEP":
                            mon = 9;
                            break;
                        case "OCT":
                            mon = 10;
                            break;
                        case "NOV":
                            mon = 11;
                            break;
                        case "DEC":
                            mon = 12;
                            break;
                    }
                    if (day == null)
                        day = "1";
                    return new DateTime(int.Parse(year) + 1900, mon, int.Parse(day));
                    #endregion
                }
                else if (strVal.Length == 8)
                {
                    #region  //Apr 1974  //1979 Jun  
                    string year = RegexHelper.GetNumber(strVal);
                    string month = strVal.Replace(year, string.Empty).Trim();
                    int mon = 0;
                    switch (month.ToUpper())
                    {
                        default:
                        case "JAN":
                            mon = 1;
                            break;
                        case "FEB":
                            mon = 2;
                            break;
                        case "MAR":
                            mon = 3;
                            break;
                        case "APR":
                            mon = 4;
                            break;
                        case "MAY":
                            mon = 5;
                            break;
                        case "JUN":
                            mon = 6;
                            break;
                        case "JUL":
                            mon = 7;
                            break;
                        case "AUG":
                            mon = 8;
                            break;
                        case "SEP":
                            mon = 9;
                            break;
                        case "OCT":
                            mon = 10;
                            break;
                        case "NOV":
                            mon = 11;
                            break;
                        case "DEC":
                            mon = 12;
                            break;
                    }
                    #endregion
                    return new DateTime(int.Parse(year), mon, 1);
                }
                else if (strVal.Length == 6)
                {
                    #region //28 May 
                    string day = RegexHelper.GetNumber(strVal);
                    string month = strVal.Replace(day, string.Empty).Trim();
                    if (day.Length == 3)
                    {
                        string t = day;
                        day = month;
                        month = t;
                    }
                    int mon = 0;
                    switch (month.ToUpper())
                    {
                        default:
                        case "JAN":
                            mon = 1;
                            break;
                        case "FEB":
                            mon = 2;
                            break;
                        case "MAR":
                            mon = 3;
                            break;
                        case "APR":
                            mon = 4;
                            break;
                        case "MAY":
                            mon = 5;
                            break;
                        case "JUN":
                            mon = 6;
                            break;
                        case "JUL":
                            mon = 7;
                            break;
                        case "AUG":
                            mon = 8;
                            break;
                        case "SEP":
                            mon = 9;
                            break;
                        case "OCT":
                            mon = 10;
                            break;
                        case "NOV":
                            mon = 11;
                            break;
                        case "DEC":
                            mon = 12;
                            break;
                    }
                    #endregion
                    return new DateTime(1900, mon, int.Parse(day));
                }
                return new DateTime(1900, 1, 1);
            }
            else
            {
                #region  //19050419 //1925

                string year = string.Join("", strVal.Take(4));
                if (string.IsNullOrEmpty(year))
                    year = "1900";
                string month = string.Join("", strVal.Skip(4).Take(2));
                if (string.IsNullOrEmpty(month))
                    month = "01";
                string day = string.Join("", strVal.Skip(6).Take(2));
                if (string.IsNullOrEmpty(day))
                    day = "01";
                #endregion
                return new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
            }

        }

        public static string yyyyMMdd_To_yyyy_MM_dd(object val, DataRow _row)
        {
            return yyyyMMdd(val, _row).ToString("yyyy-MM-dd");
        }
        public static string HHmmss_To_Time(object val, DataRow _row)
        {
            DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (NullHelper.IsDbNull(val))
            {
                return dt.ToString("HH:mm");
            }
            else
            {
                string strVal = val.ToString().PadLeft(6, '0');
                int hour = int.Parse(string.Join("", strVal.Take(2)));
                int minute = int.Parse(string.Join("", strVal.Skip(2).Take(2)));
                int sec = int.Parse(string.Join("", strVal.Skip(4).Take(2)));
                dt = dt.AddHours(hour);
                dt = dt.AddMinutes(minute);
                dt = dt.AddSeconds(sec);
                return dt.ToString("HH:mm");
            }
        }

        public static DateTime HHmmss_To_Datetime(object val, DataRow _row)
        {
            DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (NullHelper.IsDbNull(val))
            {
                return dt;
            }
            else
            {
                string strVal = val.ToString();
                int hour = int.Parse(string.Join("", strVal.Take(2)));
                int minute = int.Parse(string.Join("", strVal.Skip(2).Take(2)));
                int sec = int.Parse(string.Join("", strVal.Skip(4).Take(2)));
                dt.AddHours(hour);
                dt.AddMinutes(minute);
                dt.AddSeconds(sec);
                return dt;
            }
        }

        /// <summary> 
        /// 将c# DateTime时间格式转换为Unix时间戳格式 
        /// </summary> 
        /// <param name="time">时间</param> 
        /// <returns>long</returns> 
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位     
            return t;
        }

        /// <summary>       
        /// 时间戳转为C#格式时间    timeStamp=146471041000   
        /// </summary>       
        /// <param name=”timeStamp”></param>       
        /// <returns></returns>       
        private DateTime ConvertStringToDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        #endregion

        #region 枚举相关
        public static string Sexual_Reverse(object val, DataRow _row)
        {
            if (val == null) return string.Empty;
            string strVal = val.ToString();
            return strVal == "1" ? "0" : strVal == "0" ? "1" : "2";
        }

        public static string Get_MedicalHistoryType(object val, DataRow _row)
        {
            if (val == null) return string.Empty;
            string strVal = val.ToString();
            switch (strVal)
            {
                case "ALLERGY":
                    return "2";
                case "DRUG HISTORY":
                    return "1";
                case "IMMUNIZATION":
                    return "5";
                case "MEDICAL HISTORY":
                    return "1";
                default:
                    return "1";
            }
        }
        public static string Get_MedicalHistoryTypeName(object val, DataRow _row)
        {
            if (val == null) return string.Empty;
            string strVal = val.ToString();
            switch (strVal)
            {
                case "ALLERGY":
                    return "Allergy";
                case "IMMUNIZATION":
                    return "Immunization";
                case "MEDICAL HISTORY":
                    return "Past History";
                case "DRUG HISTORY":
                default:
                    return strVal;
            }
        }
        #endregion

        #region 状态相关

        public static string Get_Bill_Status(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return "2";
            string dec = val.ToString();
            decimal d = decimal.Parse(dec);
            if (d > 0)
            {
                return "2";
            }
            return "3";
        }
        #endregion

        #region 文件相关


        public static string Get_FileName(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return string.Empty;
            string fName = val.ToString();
            return System.IO.Path.GetFileName(fName);
        }

        public static string Get_FileExternsion(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return string.Empty;
            string fName = val.ToString();
            string ext = System.IO.Path.GetExtension(fName).ToLower();
            switch (ext)
            {
                case ".pdf":
                    return "PDF";
                case ".bmp":
                case ".jpg":
                case ".png":
                case ".jpeg":
                case ".gif":
                    return "Img";
                case ".docx":
                case ".doc":
                    return "Word";
                case ".xls":
                case ".xlsx":
                    return "Excel";
                default:
                    return "Other";
            }
        }

        #endregion

        #region 地址相关
        public class Base_Area
        {
            public int AreaId { get; set; }
            public int ParentId { get; set; }

            public string AreaCode { get; set; }
            public string AreaName { get; set; }
        }


        static List<Base_Area> _GetAllAreas()
        {
            using (IDbCommand cmd = MyDbConfig.Current.TargetConnection.CreateCommand())
            {
                cmd.CommandText = @"
SELECT  AreaId ,
        ParentId ,
        AreaCode ,
        AreaName
FROM    dbo.Base_Area
WHERE   DeleteMark = 0;
";
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    return DbHelper.FillCollectionFromReader<Base_Area>(reader);
                }
            }
        }

        public static List<Base_Area> GetAllAreas()
        {
            return CacheHelper.Get<List<Base_Area>>("GetAllAreas", _GetAllAreas, DEFAULT_CAHCE_TIME);
        }
        public static string Address_Get_CountyId(object val, DataRow _row)
        {
            return "NULL";
        }
        public static string Address_Get_ProvinceId(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {
                string strVal = val.ToString();
                string[] add = strVal.Split(',');
                string area = add.LastOrDefault();
                int aId = GetAllAreas()
                     .Where(x => string.Equals(x.AreaCode, area, StringComparison.CurrentCultureIgnoreCase)
                || string.Equals(x.AreaName, area, StringComparison.CurrentCultureIgnoreCase))
                .Select(x => x.AreaId).FirstOrDefault();
                return aId == 0 ? "NULL" : add.ToString();
            }
        }

        public static string Address_Get_CityId(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {
                string proviceIdText = Address_Get_ProvinceId(val, _row);
                int parentId = proviceIdText == "NULL" ? 0 : int.Parse(proviceIdText);
                string strVal = val.ToString();
                string[] add = strVal.Split(',');
                string area = add.Reverse().Skip(1).FirstOrDefault();
                int aId = GetAllAreas()
                    .Where(x => x.ParentId == parentId)
                     .Where(x => string.Equals(x.AreaCode, area, StringComparison.CurrentCultureIgnoreCase)
                || string.Equals(x.AreaName, area, StringComparison.CurrentCultureIgnoreCase))
                .Select(x => x.AreaId).FirstOrDefault();
                return aId == 0 ? "NULL" : add.ToString();
            }
        }

        public static string Address_Get_Detail(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {
                string strVal = val.ToString();
                string[] add = strVal.Split(',');
                string area = string.Join(",", add.Reverse().Skip(2).Reverse());
                return area;
            }
        }
        #endregion

        #region 数据字典相关
        public class Base_DataItemDetail
        {
            public string ItemDetailId { get; set; }
            public string ItemId { get; set; }
            public string ParentId { get; set; }
            public string ItemCode { get; set; }
            public string ItemName { get; set; }
            public string ItemValue { get; set; }
        }

        public static List<Base_DataItemDetail> GetAll_Base_DataItemDetail()
        {
            return CacheHelper.Get<List<Base_DataItemDetail>>("GetAll_Base_DataItemDetail", _GetAll_Base_DataItemDetail, DEFAULT_CAHCE_TIME);
        }
        static List<Base_DataItemDetail> _GetAll_Base_DataItemDetail()
        {
            using (IDbCommand cmd = MyDbConfig.Current.TargetConnection.CreateCommand())
            {
                cmd.CommandText = @"
SELECT  ItemDetailId ,
        ItemId ,
        ParentId ,
        ItemCode ,
        ItemName ,
        ItemValue
FROM    dbo.Base_DataItemDetail
WHERE   DeleteMark = 0;
";
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    return DbHelper.FillCollectionFromReader<Base_DataItemDetail>(reader);
                }
            }
        }

        public class Base_DataItem
        {
            public string ItemId { get; set; }
            public string ParentId { get; set; }
            public string ItemCode { get; set; }
            public string ItemName { get; set; }
        }

        public static List<Base_DataItem> GetAll_Base_DataItem()
        {
            return CacheHelper.Get<List<Base_DataItem>>("GetAll_Base_DataItem", _GetAll_Base_DataItem, DEFAULT_CAHCE_TIME);
        }
        static List<Base_DataItem> _GetAll_Base_DataItem()
        {
            using (IDbCommand cmd = MyDbConfig.Current.TargetConnection.CreateCommand())
            {
                cmd.CommandText = @"
SELECT  ItemId ,
        ParentId ,
        ItemCode ,
        ItemName 
FROM    dbo.Base_DataItem
WHERE   DeleteMark = 0;
";
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    return DbHelper.FillCollectionFromReader<Base_DataItem>(reader);
                }
            }
        }

        public static string Get_ServiceType(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {
                string strVal = val.ToString();
                string serviceItemId = GetAll_Base_DataItem()
                    .Where(x => String.Equals("ServiceType", x.ItemCode, StringComparison.CurrentCultureIgnoreCase))
                    .Select(x => x.ItemId)
                    .FirstOrDefault();
                string myValue = GetAll_Base_DataItemDetail()
                     .Where(x => x.ItemId == serviceItemId)
                     .Where(x => string.Equals(x.ItemName, strVal, StringComparison.CurrentCultureIgnoreCase)
                         || string.Equals(x.ItemValue, strVal, StringComparison.CurrentCultureIgnoreCase)
                     )
                     .Select(x => x.ItemDetailId)
                     .FirstOrDefault();
                return string.IsNullOrEmpty(myValue) ? "NULL" : myValue;
            }
        }

        public static string Get_SubServiceType(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {
                string ServiceType = _row["ServiceType"].ToString();
                string strVal = val.ToString();
                if (string.Equals(strVal, "PH01"))
                {

                }
                string serviceItemId = GetAll_Base_DataItem()
                    .Where(x => String.Equals("ServiceType", x.ItemCode, StringComparison.CurrentCultureIgnoreCase))
                    .Select(x => x.ItemId)
                    .FirstOrDefault();
                string ServiceTypeId = Get_ServiceType(ServiceType, _row);
                string myValue = GetAll_Base_DataItemDetail()
                     .Where(x => x.ItemId == serviceItemId)
                     .Where(x => x.ParentId == ServiceTypeId)
                     .Where(x => string.Equals(x.ItemName, strVal, StringComparison.CurrentCultureIgnoreCase)
                         || string.Equals(x.ItemValue, strVal, StringComparison.CurrentCultureIgnoreCase)
                     )
                     .Select(x => x.ItemDetailId)
                     .FirstOrDefault();
                return string.IsNullOrEmpty(myValue) ? "NULL" : myValue;
            }
        }

        public static string Get_PayServiceType(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
            {
                return "NULL";
            }
            else
            {

                string strVal = val.ToString();
                string serviceItemId = GetAll_Base_DataItem()
                    .Where(x => String.Equals("PayService", x.ItemCode, StringComparison.CurrentCultureIgnoreCase))
                    .Select(x => x.ItemId)
                    .FirstOrDefault();
                string myValue = GetAll_Base_DataItemDetail()
                     .Where(x => x.ItemId == serviceItemId)
                     .Where(x => string.Equals(x.ItemName, strVal, StringComparison.CurrentCultureIgnoreCase)
                         || string.Equals(x.ItemValue, strVal, StringComparison.CurrentCultureIgnoreCase)
                     )
                     .Select(x => x.ItemDetailId)
                     .FirstOrDefault();
                return string.IsNullOrEmpty(myValue) ? "NULL" : myValue;
            }
        }

        static string _Get_Default_FileTypeId = null;

        public static string Get_Default_FileTypeId(object val, DataRow _row)
        {
            if (_Get_Default_FileTypeId == null)
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
	  FROM dbo.Base_DataItem bdi
	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
	  WHERE bdi.ItemCode='FileType' AND did.EnabledMark=1
");
                _Get_Default_FileTypeId = items.Select(x => x.Id).FirstOrDefault();
            }
            return _Get_Default_FileTypeId;
        }

        static string _Get_Default_NurseTypeId = null;

        public static string Get_Default_NurseTypeId(object val, DataRow _row)
        {
            if (_Get_Default_NurseTypeId == null)
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
	  FROM dbo.Base_DataItem bdi
	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
	  WHERE bdi.ItemCode='ServiceType' AND did.EnabledMark=1 AND did.ItemValue='Nurse'
");
                _Get_Default_NurseTypeId = items.Select(x => x.Id).FirstOrDefault();
            }
            return _Get_Default_NurseTypeId;
        }

        static List<MyIdNameItem> _Get_Nurse_ServiceItem = null;
        [Obsolete("复杂度过高，不宜迁移")]
        public static string Get_Nurse_ServiceItem(object val, DataRow _row)
        {
            if (_Get_Nurse_ServiceItem == null)
            {
                _Get_Nurse_ServiceItem = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
	  FROM dbo.Base_DataItem bdi
	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
	  WHERE bdi.ItemCode='ServiceType' AND did.EnabledMark=1 AND did.ItemValue='Nurse'
");
            }
            return _Get_Default_NurseTypeId;
        }

        //        public static string Get_CaseTestItemsId(object val, DataRow _row)
        //        {
        //             _Get_Nurse_ServiceItem= MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
        //IF()
        //SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
        //	  FROM dbo.Base_DataItem bdi
        //	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
        //	  WHERE bdi.ItemCode='ServiceType' AND did.EnabledMark=1 AND did.ItemValue='Nurse'
        //");
        //        }


        static string _Get_Default_Goods_TypeId = null;

        public static string Get_Default_Goods_TypeId(object val, DataRow _row)
        {
            if (_Get_Default_Goods_TypeId == null)
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
	  FROM dbo.Base_DataItem bdi
	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
	  WHERE bdi.ItemCode='ItemType' AND did.EnabledMark=1 AND did.ItemValue='DisposableGoods'
");
                _Get_Default_Goods_TypeId = items.Select(x => x.Id).FirstOrDefault();
            }
            return _Get_Default_Goods_TypeId;
        }

        public static string Get_Unit_Id(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return null;
            string strVal = val.ToString();
            List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 did.ItemDetailId AS Id, did.ItemName AS Name
	  FROM dbo.Base_DataItem bdi
	  JOIN dbo.Base_DataItemDetail did ON did.ItemId=bdi.ItemId
	  WHERE bdi.ItemCode='StockUnit' AND did.EnabledMark=1 AND did.ItemValue=@P0
", strVal);
            return items.Select(x => x.Id).FirstOrDefault();
        }

        static string _Get_BloodTypeId = null;
        public static string Get_BloodTypeId(object val, DataRow _row)
        {
            if (string.IsNullOrEmpty(_Get_BloodTypeId))
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 ItemId AS Id
	  FROM dbo.Base_DataItem bdi
	  WHERE bdi.ItemCode='BloodType'
");
                _Get_BloodTypeId = items.Select(x => x.Id).FirstOrDefault();
            }
            return _Get_BloodTypeId;
        }

        static string _Get_ClientJobId = null;
        public static string Get_ClientJobId(object val, DataRow _row)
        {
            if (string.IsNullOrEmpty(_Get_ClientJobId))
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 ItemId AS Id
	  FROM dbo.Base_DataItem bdi
	  WHERE bdi.ItemCode='ClientJob'
");
                _Get_ClientJobId = items.Select(x => x.Id).FirstOrDefault();
            }
            return _Get_ClientJobId;
        }

        public static string GetUseId(object val, DataRow _row)
        {
            //ItemCode=DrugUsage
            return "'NUL'";
        }
        
        static string _GetStrengthUnit = null;
        public static string GetStrengthUnit(object val, DataRow _row)
        {
             if (string.IsNullOrEmpty(_GetStrengthUnit))
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 ItemId AS Id
	  FROM dbo.Base_DataItem bdi
	  WHERE bdi.ItemCode='StrengthUnit'
");
                _GetStrengthUnit = items.Select(x => x.Id).FirstOrDefault();
            }
            return _GetStrengthUnit;
        }

        
        static string _GetStockUnit = null;
        public static string GetStockUnit(object val, DataRow _row)
        {
             if (string.IsNullOrEmpty(_GetStockUnit))
            {
                List<MyIdNameItem> items = MyDbHelper.FindListFromTarget<MyIdNameItem>(@"
SELECT TOP 1 ItemId AS Id
	  FROM dbo.Base_DataItem bdi
	  WHERE bdi.ItemCode='StrengthUnit'
");
                _GetStockUnit = items.Select(x => x.Id).FirstOrDefault();
            }
            return _GetStockUnit;
        }
        #endregion

        #region 库存相关
        public class InStock
        {
            public string Id { get; set; }
            public string Z__D_NAME { get; set; }
            public DateTime Z__TIMESTAMP { get; set; }
            public string Z__DATE { get; set; }
            public string Z__CLINICCODE { get; set; }
        }

        public static List<InStock> GetAll_InStock()
        {
            return CacheHelper.Get<List<InStock>>("GetAll_InStock", _GetAll_InStock, DEFAULT_CAHCE_TIME);

        }

        static readonly TimeSpan DEFAULT_CAHCE_TIME = new TimeSpan(7, 0, 0, 0);

        static List<InStock> _GetAll_InStock()
        {
            using (IDbCommand cmd = MyDbConfig.Current.TargetConnection.CreateCommand())
            {
                cmd.CommandText = @"
SELECT  Id ,
        Z__D_NAME ,
        Z__TIMESTAMP ,
        Z__DATE,
     Z__CLINICCODE
FROM    dbo.Base_DataItem
WHERE  Z__TIMESTAMP IS NOT NULL;
";
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    return DbHelper.FillCollectionFromReader<InStock>(reader);
                }
            }
        }

        static bool Is_Equals(string x, string y)
        {
            if (string.IsNullOrEmpty(x) || x == "NULL")
            {
                if (string.IsNullOrEmpty(y) || y == "NULL")
                    return true;
                return false;
            }
            return string.Equals(x, y, StringComparison.CurrentCultureIgnoreCase);
        }

        public static string GET_InStockId(object val, DataRow _row)
        {
            InStock now = new InStock()
            {
                Z__CLINICCODE = _row["Z__CLINICCODE"].ToString()
                ,
                Z__DATE = _row["Z__DATE"].ToString()
                ,
                Z__D_NAME = _row["Z__D_NAME"].ToString()
                ,
                Z__TIMESTAMP = DateTime.Parse(_row["Z__TIMESTAMP"].ToString())
            };
            return GetAll_InStock()
                .Where(x => x.Z__TIMESTAMP.Ticks == now.Z__TIMESTAMP.Ticks
                && Is_Equals(x.Z__D_NAME, now.Z__D_NAME)
                && Is_Equals(x.Z__DATE, now.Z__DATE)
                && Is_Equals(x.Z__CLINICCODE, now.Z__CLINICCODE))
                .Select(x => x.Id)
                .FirstOrDefault();
        }
        #endregion

        #region 药品相关
        public static decimal Get_IntOfMedicialUseMethod(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return 0;
            string strVal = val.ToString();
            if (RegexHelper.IsNumber(strVal))
            {
                return decimal.Parse(strVal);
            }
            switch (strVal)
            {
                case "1-2":
                    return 1.5M;
                case "1W": return -1M;
                case "2-3": return -1M;
                case "2W": return -1M;
                case "3-4": return -1M;
                case "3DA": return -1M;
                case "3W": return -1M;
                case "4-5": return -1M;
                case "4W": return -1M;
                case "5W": return -1M;
                case "ASORDER": return -1M;
                case "BID": return -1M;
                case "BIW": return -1M;
                case "E12": return -1M;
                case "E4": return -1M;
                case "E6": return -1M;
                case "E6-PRN": return -1M;
                case "E8": return -1M;
                case "EOD": return -1M;
                case "HS": return -1M;
                case "MANE": return -1M;
                case "NOCT": return -1M;
                case "OPD": return -1M;
                case "PRN": return -1M;
                case "Q1H": return -1M;
                case "QAD": return -1M;
                case "QD": return -1M;
                case "QID": return -1M;
                case "QOD": return -1M;
                case "QW": return -1M;
                case "STAT": return -1M;
                case "TID": return -1M;
                case "X": return -1M;
                default:
                    return 0M;
            }
        }

        public static decimal Get_Decimal(object val, DataRow _row)
        {
            if (NullHelper.IsDbNull(val))
                return 0;
            string strVal = val.ToString();
            if (RegexHelper.IsNumber(strVal))
            {
                return decimal.Parse(strVal);
            }
            string number = RegexHelper.GetNumber(strVal);
            if (RegexHelper.IsNumber(number))
            {
                return decimal.Parse(number);
            }
            return 0M;
        }

        #endregion


        public static decimal Get_OnePercent(object val, DataRow _row)
        {
            return Get_Decimal(val, _row) / 100;
        }

        #region 编码相关

        public static string Get_Code(object val, DataRow _row)
        {
            DateTime dt = DateTime.MinValue;
            if (!NullHelper.IsDbNull(val))
            {
                string strVal = val.ToString();
                dt = DateTime.Parse(strVal);
            }
            return $"{_row["Z__CLINICCODE"]}{dt.ToString("yyyyMMddHHmm")}";
        }
        #endregion
    }
}
